;(function ($, global) {
  let _token = $('input[name=_token]').eq(0).val()

  let req = new FormData()
  let URL = global.URL || global.webkitURL
  let Cropper = global.Cropper
  let $modal = $('#slider-add-modal')
  let $form = $modal.find('#slider-add-form')
  let $submit = $modal.find('#slider-add-submit')
  let $file = $form.find('input[name=img]')
  let $cropperGroup = $form.find('.form-cropper')
  let $cropperControl = $form.find('.form-cropper-control')
  let $cropperPreview = $form.find('.form-preview')
  let $image = $('#image')
  let originalImageURL = $image.attr('src')
  let uploadedImageType = 'image/jpeg'
  let uploadedImageURL
  let $crop
  let minContainerWidth = 538

  let $deleteSpan = $('.slider-delete-span')
  let $addSpan = $('.slider-add-span')
  let options = {
    viewMode: 2,
    preview: '.img-preview',
    aspectRatio: 16 / 9,
    minContainerWidth: minContainerWidth,
    minContainerHeight: 1000,
    crop: function (e) {},
    ready: function () {
      fnStopLoading()
      $cropperGroup.show()
      $cropperControl.show()
      $cropperPreview.show()
    }
  }

  let verifyAdd = {
    title: {
      required: true,
      errMsg: '标题不能为空'
    },
    intro: {
      required: true,
      errMsg: '描述不能为空'
    },
    type: {
      required: true,
      errMsg: '类型不能为空'
    },
    rank: {
      required: true,
      pattern : /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/,
      errMsg: '排序数值不合法'
    },
    slider_img: {
      required: true,
      errMsg: '图片不能为空'
    }
  }

  let fnInitReq = function () {
    return new FormData($form[0])
  }

  let fnInitAddReq = function () {
    let data = new FormData($form[0])
    data.delete('img')
    let imageData
    try {
      imageData = $image.cropper('getCroppedCanvas').toBlob(function (blob) {
        data.append('slider_img', blob)
        req = data
      }, uploadedImageType, 1)
    } catch (e) {
      req = data
    }
  }

  let fnAddFormInits = function ($span, $form) {
    $form.find('select[name=type]').val($span.attr('data-type'))
  }

  let fnTrigger = function () {
    $file.change(function () {
      var files = this.files
      var file
      if (files && files.length) {
        file = files[0]
        if (/^image\/\w+$/.test(file.type)) {
          uploadedImageType = file.type
          if (uploadedImageURL) {
            URL.revokeObjectURL(uploadedImageURL)
          }
          uploadedImageURL = URL.createObjectURL(file)
          $image.cropper('destroy').attr('src', uploadedImageURL)
          $image[0].onload = function () {
            let width = this.width
            let height = this.height
            options.minContainerHeight = options.minContainerWidth * height / width
            $image.cropper(options)
          }
          global.cropimg = $image
          fnCropScaleInit()
          $file.val('')
        } else {
          layer.msg('Please choose an image file.')
        }
      }
    })

    $submit.click(function () {
      let data = new FormData($form[0])
      data.delete('img')
      try {
        imageData = $image.cropper('getCroppedCanvas').toBlob(function (blob) {
          data.append('slider_img', blob)
          let objData = {}
          data.forEach((value, key) => {
            objData[key] = value;})
          if (reqVerify(objData, verifyAdd)) {
            fnLoading()
            fnAddSlider(data, fnAddSuccess, fnAddError)
          }
        }, uploadedImageType)
      } catch (e) {
        layer.msg('请选择图片')
      }
    })

    $deleteSpan.click(function () {
      $this = $(this)
      let id = $this.attr('data-id')
      let data = {
        id: id,
        s: 1,
        _token: _token
      }
      fnDelConfirm(data)
    })

    $addSpan.click(function () {
      $this = $(this)
      fnAddFormInits($this, $form)
    })
  }

  let fnUploadImg = function (data, suc, err) {
    fnUploadAjax('POST', 'upload/img', data, 'json', suc, err)
  }

  let fnAddSlider = function (data, suc, err) {
    fnUploadAjax('POST', 'slider/add', data, 'json', suc, err)
  }

  let fnDelSlider = function (data, suc, err) {
    fnApiAjax('POST', 'slider/del', data, 'json', suc, err)
  }

  let fnUploadSuccess = function (data) {
    fnImageClear()
    $form.find('input[name=path]').val(data.path)
    fnImageDownload(data.url)
  }

  let fnImageClear = function () {
    if ($image) {
      $image.cropper('destroy').hide()
    }
  }

  let fnImageDownload = function (url) {
    var img = new Image()
    img.src = url
    $(img).attr('id', 'image')
    img.onload = function () {
      //   var size = this.width / this.height
      //   var width = size * 360
      //   this.width = width
      //   this.height = 360
    }
    $cropperGroup.append(img)
    fnImageCropper()
    fnCropScaleInit()
  }

  let fnImageCropper = function () {
    $crop = $form.find('input[name=crop]')
    $image = $('#image')
    global.cropimg = $image
    $image.cropper(options)
  }

  let fnUploadError = function () {
    fnStopLoading()
  }

  let fnCropScaleInit = function () {
    global.scaleX = 1
    global.scaleY = 1
  }

  let fnAddFormInit = function () {
    $cropperGroup.hide()
    $cropperControl.hide()
    $cropperPreview.hide()
    $image.cropper('destroy')
    $form[0].reset()
  }

  let fnAddSuccess = function (data) {
    $modal.modal('hide')
    layer.msg('新增成功')
    fnReload()
  }

  let fnAddError = function () {}

  let fnDelSuccess = function (data) {
    layer.msg('删除成功', {icon: 1})
    $('#slider-' + data.id).fadeTo('slow', 0.01, function () { // fade
      $(this).slideUp('slow', function () { // slide up
        $(this).remove()
      })
    })
  }

  let fnDelError = function () {}

  let fnDelConfirm = function (data) {
    layer.confirm('确定删除此项？', {
      btn: ['确定', '取消'] // 按钮
    }, function () {
      fnLoading()
      fnDelSlider(data, fnDelSuccess, fnDelError)
    }, function () {})
  }

  global.fnAddFormInit = fnAddFormInit

  fnTrigger()
})(jQuery, window)

// 轮播图修改
;(function ($, global) {
  let $modal = $('#slider-edit-modal')
  let $form = $modal.find('#slider-edit-form')
  let $editSpan = $('.slider-edit-span')
  let $submit = $modal.find('#slider-edit-submit')

  let verify = {
    title: {
      required: true,
      errMsg: '标题不能为空'
    },
    intro: {
      required: true,
      errMsg: '描述不能为空'
    },
    type: {
      required: true,
      errMsg: '类型不能为空'
    },
    rank: {
      required: true,
      pattern : /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/,
      errMsg: '排序数值不合法'
    },
  }

  let fnEditFormInit = function ($span, $form) {
    $form.find('input[name=id]').val($span.attr('data-id'))
    $form.find('select[name=type]').val($span.attr('data-type'))
    $form.find('input[name=title]').val($span.attr('data-title'))
    $form.find('input[name=intro]').val($span.attr('data-intro'))
    $form.find('input[name=rank]').val($span.attr('data-rank'))
    let status = $span.attr('data-status')
    $form.find("input[name='status'][value='" + status + "']").prop('checked', 'checked')
    $form.find('img.img').attr('src', $span.attr('data-img')).attr('alt', $span.attr('data-title')).attr('title', $span.attr('data-title'))
  }

  let fnInitEditReq = function ($form) {
    return {
      _token: $form.find('input[name=_token]').val(),
      id: $form.find('input[name=id]').val(),
      type: $form.find('select[name=type]').val(),
      title: $form.find('input[name=title]').val(),
      intro: $form.find('input[name=intro]').val(),
      rank: $form.find('input[name=rank]').val(),
      status: $form.find('input[name=status]:checked').val()
    }
  }

  let fnEditAjax = function (data) {
    fnApiAjax('POST', 'slider/edit?id=' + data.id, data, 'json', fnCommonEditSuccess, fnCommonEditError)
  }

  let fnTrigger = function () {
    $editSpan.click(function () {
      $this = $(this)
      fnEditFormInit($this, $form)
    })

    $submit.click(function () {
      let req = fnInitEditReq($form)
      if (reqVerify(req, verify)) {
        fnBtnDisable($(this))
        fnLoading()
        fnEditAjax(req)
      }
    })
  }

  fnTrigger()
})(jQuery, window)
